package com.example.filter;

import com.example.utils.JwtTokenProvider;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.beans.factory.ObjectProvider;

import java.io.IOException;

/**
 * JWT身份验证过滤器，用于处理JWT令牌并设置身份验证信息
 * 继承OncePerRequestFilter以确保每次请求只执行一次过滤
 */
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    // JWT令牌提供者，用于处理JWT令牌的生成、解析和验证
    private final JwtTokenProvider tokenProvider;
    // 用户详细信息提供者，用于根据用户名获取用户详细信息
    // 使用ObjectProvider以支持延迟获取UserDetailsService实例
    private final ObjectProvider<UserDetailsService> userDetailsService;

    /**
     * 执行实际的过滤逻辑
     * 从HTTP请求中获取JWT令牌，验证令牌有效性，设置身份验证信息
     *
     * @param request     HTTP请求
     * @param response    HTTP响应
     * @param filterChain 过滤链，用于将请求传递给下一个过滤器或目标
     * @throws ServletException 如果过滤过程中发生Servlet异常
     * @throws IOException      如果过滤过程中发生I/O异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {

        // 从请求中获取JWT令牌
        String token = getJwtFromRequest(request);

        // 如果令牌存在且有效，则设置身份验证信息
        if (StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
            // 从令牌中获取用户名
            String username = tokenProvider.getUsernameFromToken(token);

            // 延迟获取UserDetailsService实例并加载用户详细信息
            UserDetails userDetails = userDetailsService.getIfAvailable()
                    .loadUserByUsername(username);

            // 创建身份验证令牌并设置用户详细信息
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(
                            userDetails,
                            null,
                            userDetails.getAuthorities());

            // 设置身份验证详细信息
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            // 将身份验证令牌设置到SecurityContext中
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        // 继续执行过滤链
        filterChain.doFilter(request, response);
    }

    /**
     * 从HTTP请求中提取JWT令牌
     * 仅处理"Authorization"头以"Bearer "开头的情况
     *
     * @param request HTTP请求
     * @return 提取的JWT令牌，如果没有找到或格式不正确则返回null
     */
    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
